﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using MySoft.Data;
using Common.Utilities.Excel.Export;
using System.IO;
using System.Data;
using Common.Utilities.Excel;
using ShareMarking.Interface;
using System.Configuration;
using System.Net;
using System.Drawing.Imaging;
using ShareMarking.Services;

namespace ShareMarking.Web.admin.EnterPrise.QrStore
{
    public partial class Index : ManagePage
    {


        #region 参数配置=================================

        private string httpstr = ConfigurationManager.AppSettings["vigohttp"];
        private string signsecret = ConfigurationManager.AppSettings["signscrect"];

        protected int totalCount;
        protected int page;
        //protected string S_name = string.Empty;
        protected string pageSizeCookieKey = "qr_Store_index_page_size";//当前页的每页大小的cookiekey
        protected int pageSize
        {
            get
            {
                int _default_size = 10;
                int _pagesize;
                if (int.TryParse(Utils.GetCookie(pageSizeCookieKey), out _pagesize))
                {
                    if (_pagesize > 0)
                    {
                        return _pagesize;
                    }
                }
                return _default_size;
            }
        }
        protected string orderBy = "qr_Store.StoreCode desc";

        protected string keywords = string.Empty;
        protected string searchURL { get { return Utils.CombUrlTxt("Index.aspx", "keywords={0}", this.keywords); } }

        #endregion

        #region 初始化===================================

        protected void Page_Load(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString());

            //初始化搜索参数
            this.keywords = DTRequest.GetQueryString("keywords");

            if (!Page.IsPostBack)
            {
                //绑定下拉框的值

                //绑定列表
                RptBind();
            }
        }

        #endregion

        #region 绑定下拉框===============================

        #endregion

        #region 绑定列表=================================
        private void RptBind()
        {
            this.page = DTRequest.GetQueryInt("page", 1);

            //获取数据源
            if (!keywords.IsNullOrEmpty())
            {
                this.txtKeywords.Text = keywords;
            }
            this.rptList.DataSource = qr_StoreService.Instance.Get_qr_Store_PageSelect(page, pageSize, orderBy, out totalCount, keywords);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = ComLib.UrlHelper.Instance.SetUrl(searchURL).AddParam("page", "__id__").GetAddedParamUrl();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 搜索操作=================================

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.keywords = txtKeywords.Text;
            Response.Redirect(searchURL);
        }

        //筛选类别
        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie(pageSizeCookieKey, _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(searchURL);
        }

        protected void btnDetailedSearch_Click(object sender, EventArgs e)
        {
            //this.A_Name = txtA_Name.Text;
            //this.A_Manager = txtA_Manager.Text;
            Response.Redirect(searchURL);
        }

        #endregion

        #region 删除操作=================================

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.Delete.ToString());

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (qr_StoreService.Instance.Delete_Entity(qr_Store._.StoreCode == id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }

            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除qr_Store" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        #endregion

        #region 导出成Excel表格==================

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();
                //DataTable table = DbSession.Default.From<qr_Store>().Select(qr_Store._.S_Name, qr_Store._.S_Provinces, qr_Store._.S_City, qr_Store._.S_Area, qr_Store._.S_Region, qr_Store._.CreateOn).ToTable();
                DataTable table = new DataTable();
                string sql = @"select storecode,s_name,s_provinces,s_city,s_area,s_region,qr.scene_id,qr.qrcode_url from qr_Store store left join qr_QrCodeRelate rel on store.StoreCode=rel.rel_Code left join qr_QrCode qr on rel.qr_Scene_ID=qr.scene_id where store.a_sacode is  null order by store.StoreCode desc";
                table = DbSession.Default.FromSql(sql).ToTable();
                table.TableName = "qr_Store";
                ds.Tables.Add(table);

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("ExportCode_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "storeinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                WriteLog.WriteError(ex.ToString());
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出门店信息" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        protected void ConfigExportValidate(ExcelExportProvider provider, DataSet container, string typeName)
        {
            ///验证数据容器中是否存在DataTable
            if (container.Tables.Count == 0) throw new Exception("DataSet对象容器中没有任何DataTable对象!");
            ///验证导入配置中的配置节是否存在
            if (provider == null) throw new Exception(string.Format("配置中不存在类型为:{0}的导入配置项!", typeName));
            ///验证配置节中是否包含至少1个worksheet
            if (provider.Worksheets == null || provider.Worksheets.Count == 0) throw new Exception(string.Format("配置中类型为:{0}的配置节中不包含Worksheet的定义", typeName));
            // 验证数据容器中存在配置节中配置的datatable
            foreach (var worksheet in provider.Worksheets)
            {
                foreach (Area area in worksheet.Areas)
                    if (!container.Tables.Contains(area.DataTable))
                        throw new Exception(string.Format("DataTable中不包含表 {0}", area.DataTable));
            }
        }
        #endregion

        #region 生成二维码
        public string GetQRCode(string StoreCode)
        {
            var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(qr_QrCodeRelate._.qr_Type == "1002" &&
                qr_QrCodeRelate._.rel_Code == StoreCode);
            if (relate != null)
            {
                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == relate.qr_Scene_ID);
                if (qrcode != null)
                    return qrcode.qrcode_url;
                return "";
            }
            return "";
        }
        #endregion

        protected void sync_click(object sender, EventArgs e)
        {
            //Sync_QrCode();//3图文
            Sync_QrCode2();//单图文
        }

        #region 生成二维码
        public void Sync_QrCode()
        {
            //两个特殊的入口
            //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(
            //    qr_Store._.StoreCode == "02LHCDL" || qr_Store._.StoreCode == "03LHfriend", null);
            #region 初始化变量
            int SuccessCount = 0;
            int ErroCount = 0;
            string info = "";
            #endregion
            //先得到所有的需要更新二维码的NC
            var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupdate == true, null);

             var result = false;
            ComLib.LogLib.Log4NetBase.Log("1-1、---------------查询得到门店共" + nclist.Count + "条---------------");
            for (int i = 0; i < nclist.Count; i++)
            {
                var o = nclist[i];
                ComLib.LogLib.Log4NetBase.Log("1-2、---------------正在执行第(" + i + ")条数据---------------");

                #region MyRegion

                var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                if (!has)
                {
                    #region 如果在关联表没有NC对应的记录，就新增二维码

                    //查询是否有以前弃用的二维码
                    var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 1002 &&
                        qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);

                    if (oldqr.IsNullOrCountLTE0())
                    {
                        #region get sceneid
                        var sceneid = 0;
                        qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1002);
                        sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                        #endregion

                        #region 编辑图文信息
                        //var extra = new List<extra>() { 
                        //        new extra { 
                        //            title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                        //            shortdesc="",
                        //            linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                        //            picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                        //        }
                        //    };
                        var extra = new List<extra>() { 
                                new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                            };
                        var message = new message()
                        {
                            title = o.StoreCode + "的二维码",
                            remark = o.StoreCode + "的二维码",
                            sacode = "test",
                            scene_id = sceneid,
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.CreateQrcode(message);
                        #endregion

                        while (resultentity.errcode == "12")
                        {
                            ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.errmsg + "/sceneid=" + sceneid);
                            sceneid += 1;
                            message.scene_id = sceneid;
                            resultentity = vigo.CreateQrcode(message);
                        }

                        #region 将返回的信息保存
                        if (resultentity.errcode == "00")
                        {
                            #region 保存二维码
                            qr_QrCode qrcode = new qr_QrCode()
                            {
                                id = resultentity.message.id,
                                type = 1002,
                                scene_id = resultentity.message.scene_id,
                                sacode = resultentity.message.sacode,
                                title = resultentity.message.title,
                                remark = resultentity.message.remark,
                                code_url = resultentity.message.code_url,
                                qrcode_url = resultentity.message.qrcode_url,
                                addtime = resultentity.message.addtime,
                                status = resultentity.message.status,
                                DateModified = DateTime.Now,
                                //wx_title = "美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                                //wx_content = "",
                                //wx_url = "http://wx.ismartgo.com/app/lighthouse/index.aspx?from=" + o.StoreCode + "$openid=####",
                                //wx_imgurl = "http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg",

                                wx_title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇",
                                wx_content = "一键注册，终身礼遇",
                                wx_url = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####",
                                wx_imgurl = "http://admin.mjn.howjoin.com/images/p1.jpg",
                                isdelete = false
                            };
                            qr_QrCodeService.Instance.Add_Entity(qrcode);
                            #endregion

                            #region 添加关联
                            qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                            {
                                qr_Type = 1002,//1002是门店
                                qr_CodeID = resultentity.message.id,
                                qr_Scene_ID = resultentity.message.scene_id,
                                rel_Code = o.StoreCode,
                                IsDelete = false,
                                CreateOn = DateTime.Now
                            };
                            qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                            #endregion

                            #region 更改二维码类型表
                            type.QT_CurrentIndex = sceneid;
                            type.QT_Used = type.QT_Used + 1;
                            type.QT_Surplus = type.QT_Surplus - 1;
                            qr_QrCodeTypeService.Instance.Update_Entity(type);
                            #endregion
                        }
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("3、====更新门店二维码========新增===门店编号:" + o.StoreCode + "::==sceneid==" + resultentity.message.scene_id);
                    }
                    else
                    {
                        #region 更新
                        var qr = oldqr[0];

                        #region 更新二维码

                        #region 编辑图文信息
                        //var extra = new List<extra>() { 
                        //        new extra { 
                        //            title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                        //            shortdesc="",
                        //            linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                        //            picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                        //        }
                        //    };
                        var extra = new List<extra>() { 
                                new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                            };
                        var message = new message2()
                        {
                            id = qr.id.ToString(),
                            title = o.S_Name,
                            remark = o.S_Name + "的二维码",
                            sacode = "test",
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.UpdateQrcode(message);
                        #endregion
                        #endregion

                        #region 新建关联
                        qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                        {
                            qr_Type = 1002,//1是NC
                            qr_CodeID = qr.id,
                            qr_Scene_ID = qr.scene_id,
                            rel_Code = o.StoreCode,
                            IsDelete = false,
                            CreateOn = DateTime.Now
                        };
                        qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("Store，使用旧的二维码：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    #region 如果有了二维码，也更新一次
                    var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                    if (relate != null)
                    {
                        var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                        if (qrcode != null)
                        {
                            #region 更新二维码

                            #region 编辑图文信息
                            //var extra = new List<extra>() { 
                            //    new extra { 
                            //        title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                            //        shortdesc="",
                            //        linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                            //        picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                            //    }
                            //};
                            var extra = new List<extra>() { 
                                new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                            };
                            var message = new message2()
                            {
                                id = qrcode.id.ToString(),
                                title = o.StoreCode,
                                remark = o.StoreCode + "的二维码",
                                sacode = "test",
                                extra = extra
                            };
                            #endregion

                            #region 请求vigo 生成二维码
                            var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                            var resultentity = vigo.UpdateQrcode(message);
                            #endregion
                            #endregion

                            ComLib.LogLib.Log4NetBase.Log("Store二维码修改：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + relate.qr_Scene_ID);
                        }
                    }
                    #endregion
                }
                #endregion

                o.isneedupdate = false;
                if (qr_StoreService.Instance.Update_Entity(o))
                {
                    SuccessCount += 1;
                }
                else
                {
                    ErroCount += 1;
                    ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新门店失败::" + info + "---------------");
                }
            }
            ComLib.LogLib.Log4NetBase.Log("1-4、---------------更新门店结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------");
        }

        public void Sync_QrCode2()
        {
            //两个特殊的入口
            //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(
            //    qr_Store._.StoreCode == "02LHCDL" || qr_Store._.StoreCode == "03LHfriend", null);
            #region 初始化变量
            int SuccessCount = 0;
            int ErroCount = 0;
            string info = "";
            #endregion
            //先得到所有的需要更新二维码的NC
            var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupdate == true, qr_Store._.StoreCode.Desc);

            var result = false;
            ComLib.LogLib.Log4NetBase.Log("1-1、---------------查询得到门店共" + nclist.Count + "条---------------");
            for (int i = 0; i < nclist.Count; i++)
            {
                var o = nclist[i];
                ComLib.LogLib.Log4NetBase.Log("1-2、---------------正在执行第(" + i + ")条数据---------------");

                #region MyRegion

                var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                if (!has)
                {
                    #region 如果在关联表没有NC对应的记录，就新增二维码

                    //查询是否有以前弃用的二维码
                    var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 1002 &&
                        qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);

                    if (oldqr.IsNullOrCountLTE0())
                    {
                        #region get sceneid
                        var sceneid = 0;
                        qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1002);
                        sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                        #endregion

                        #region 编辑图文信息
               
                        var extra = new List<extra>() {
                            new extra { 
                                        title = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑", 
                                        shortdesc = "", 
                                        linkurl = "https://lhloyalty.otype.com/?shopId="+o.StoreCode+"$shopName="+o.S_Name+"", //?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####",
                                        picurl = "http://admin.mjn.howjoin.com/images/store.jpg" 
                                    }
                                //new extra { 
                                //        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                //        shortdesc = "一键注册，终身礼遇", 
                                //        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                //        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                //    }
                                    //,
                                    //new extra{
                                    //    title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                    //    shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    //},
                                    //new extra{
                                    //    title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                    //    shortdesc = "惊喜连连，准备好了么？", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    //}
                            };
                        var message = new message()
                        {
                            title = o.StoreCode + "的二维码",
                            remark = o.StoreCode + "的二维码",
                            sacode = "test",
                            scene_id = sceneid,
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.CreateQrcode(message);
                        #endregion

                        while (resultentity.errcode == "12")
                        {
                            ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.errmsg + "/sceneid=" + sceneid);
                            sceneid += 1;
                            message.scene_id = sceneid;
                            resultentity = vigo.CreateQrcode(message);
                        }

                        #region 将返回的信息保存
                        if (resultentity.errcode == "00")
                        {
                            #region 保存二维码
                            qr_QrCode qrcode = new qr_QrCode()
                            {
                                id = resultentity.message.id,
                                type = 1002,
                                scene_id = resultentity.message.scene_id,
                                sacode = resultentity.message.sacode,
                                title = resultentity.message.title,
                                remark = resultentity.message.remark,
                                code_url = resultentity.message.code_url,
                                qrcode_url = resultentity.message.qrcode_url,
                                addtime = resultentity.message.addtime,
                                status = resultentity.message.status,
                                DateModified = DateTime.Now,

                                wx_title = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑",
                                wx_content = "一键注册，终身礼遇",
                                wx_url = "https://lhloyalty.otype.com/?shopId=" + o.StoreCode + "$shopName=" + o.S_Name + "",
                                wx_imgurl = "http://admin.mjn.howjoin.com/images/store.jpg",
                                isdelete = false
                            };
                            qr_QrCodeService.Instance.Add_Entity(qrcode);
                            #endregion

                            #region 添加关联
                            qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                            {
                                qr_Type = 1002,//1002是门店
                                qr_CodeID = resultentity.message.id,
                                qr_Scene_ID = resultentity.message.scene_id,
                                rel_Code = o.StoreCode,
                                IsDelete = false,
                                CreateOn = DateTime.Now
                            };
                            qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                            #endregion

                            #region 更改二维码类型表
                            type.QT_CurrentIndex = sceneid;
                            type.QT_Used = type.QT_Used + 1;
                            type.QT_Surplus = type.QT_Surplus - 1;
                            qr_QrCodeTypeService.Instance.Update_Entity(type);
                            #endregion
                        }
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("3、====更新门店二维码========新增===门店编号:" + o.StoreCode + "::==sceneid==" + resultentity.message.scene_id);
                    }
                    else
                    {
                        #region 更新
                        var qr = oldqr[0];

                        #region 更新二维码

                        #region 编辑图文信息
                        
                        var extra = new List<extra>() { 
                            new extra { 
                                        title = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑", 
                                        shortdesc = "", 
                                        linkurl = "https://lhloyalty.otype.com/?shopId="+o.StoreCode+"$shopName="+o.S_Name+"", //?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####",
                                        picurl = "http://admin.mjn.howjoin.com/images/store.jpg" 
                                    }
                                //new extra { 
                                //        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                //        shortdesc = "一键注册，终身礼遇", 
                                //        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                //        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                //    }
                                    //,
                                    //new extra{
                                    //    title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                    //    shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    //},
                                    //new extra{
                                    //    title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                    //    shortdesc = "惊喜连连，准备好了么？", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    //}
                            };
                        var message = new message2()
                        {
                            id = qr.id.ToString(),
                            title = o.S_Name,
                            remark = o.S_Name + "的二维码",
                            sacode = "test",
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.UpdateQrcode(message);
                        #endregion
                        #endregion

                        #region 新建关联
                        qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                        {
                            qr_Type = 1002,
                            qr_CodeID = qr.id,
                            qr_Scene_ID = qr.scene_id,
                            rel_Code = o.StoreCode,
                            IsDelete = false,
                            CreateOn = DateTime.Now
                        };
                        qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                        #endregion
                        if (resultentity.IndexOf("成功") > 0)
                        {
                            ComLib.LogLib.Log4NetBase.Log("Store，使用旧的二维码成功：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                        }
                        else
                        {
                            ComLib.LogLib.Log4NetBase.Log("Store使用旧的二维码失败：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                        }
                        
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    #region 如果有了二维码，也更新一次
                    var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                    if (relate != null)
                    {
                        var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                        if (qrcode != null)
                        {
                            #region 更新二维码

                            #region 编辑图文信息

                            var extra = new List<extra>() { 
                                new extra { 
                                        title = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑", 
                                        shortdesc = "", 
                                        linkurl = "https://lhloyalty.otype.com/?shopId="+o.StoreCode+"$shopName="+o.S_Name+"", //?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####",
                                        picurl = "http://admin.mjn.howjoin.com/images/store.jpg" 
                                    }
                                //new extra { 
                                //        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                //        shortdesc = "一键注册，终身礼遇", 
                                //        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                //        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                //    }
                                    //,
                                    //new extra{
                                    //    title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                    //    shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    //},
                                    //new extra{
                                    //    title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                    //    shortdesc = "惊喜连连，准备好了么？", 
                                    //    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                    //    picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    //}
                            };
                            var message = new message2()
                            {
                                id = qrcode.id.ToString(),
                                title = o.StoreCode,
                                remark = o.StoreCode + "的二维码",
                                sacode = "test",
                                extra = extra
                            };
                            #endregion

                            #region 请求vigo 生成二维码
                            var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                            var resultentity = vigo.UpdateQrcode(message);
                            if (resultentity.IndexOf("成功") > 0)
                            {
                                ComLib.LogLib.Log4NetBase.Log("Store二维码修改成功：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + relate.qr_Scene_ID);
                            }
                            else
                            {
                                ComLib.LogLib.Log4NetBase.Log("Store二维码修改失败：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + relate.qr_Scene_ID);
                            }
                            #endregion
                            #endregion


                        }
                    }
                    else {
                        ErroCount += 1;
                        ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新门店失败::" + info + "---------------");
                    }
                    #endregion
                }
                #endregion

                o.isneedupdate = false;
                if (qr_StoreService.Instance.Update_Entity(o))
                {
                    SuccessCount += 1;
                }
                else
                {
                    ErroCount += 1;
                    ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新门店失败::" + info + "---------------");
                }
            }
            ComLib.LogLib.Log4NetBase.Log("1-4、---------------更新门店结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------");
        }
        #endregion

        protected void exportIMG_Click(object sender, EventArgs e)
        {
            var info = "";
            try
            {
                #region 初始化变量

                int SuccessCount = 0;
                int ErroCount = 0;
                WebClient my = new WebClient();
                int HttpCode = 0;
                #endregion

                #region 查询门店图片列表
                //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.StoreCode == "20269405" || qr_Store._.StoreCode == "20607840", null);
                var nclist = qr_StoreService.Instance.Get_Entity_byWhere(
                    qr_Store._.isneedupload == true, null);
                ComLib.LogLib.Log4NetBase.Log("1、---------------导出门店图片开始,总共::" + nclist.Count + "条数据---------------");


                if (nclist.Count > 0)
                {
                    string virtulPath = "/upload/storeimg/" + DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
                    var path = System.Web.HttpContext.Current.Request.MapPath(virtulPath + "/");
                    //path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
                    //1.检查保存的物理路径是否存在，不存在则创建
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    //2.Zip打包路径 
                    string zipPath = Utils.GetMapPath(virtulPath);

                    //3.保存图片
                    #region 循环遍历保存图片
                    for (int i = 0; i < nclist.Count; i++)
                    {
                        var o = nclist[i];
                        bool result = false;
                        ComLib.LogLib.Log4NetBase.Log("2、---------------正在执行第(" + i + ")条数据---------------");
                        #region 查询关联表qr_Type == 1002
                        var entity = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                            qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.StoreCode);
                        #endregion

                        if (entity != null)
                        {
                            #region 查询微信url，保存图片进文件夹
                            info = "门店ID:" + o.StoreCode + "//门店名称:" + o.S_Name;
                            var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == entity.qr_CodeID);
                            if (qrcode != null)
                            {
                                #region 检验URL是否可访问
                                HttpCode = zip_http.GetStatusCode(qrcode.qrcode_url);
                                if (HttpCode == 200)
                                {
                                    byte[] mybyte;
                                    mybyte = my.DownloadData(qrcode.qrcode_url);
                                    MemoryStream ms = new MemoryStream(mybyte);
                                    System.Drawing.Image img;
                                    img = System.Drawing.Image.FromStream(ms);
                                    string newFileName = path + o.StoreCode + "-" + o.S_Name.Replace("?", "").Replace("？", "").Replace("<", "").Replace(">", "").Replace(":", "").Replace("*", "") + ".png"; //文件名
                                    string newpath = newFileName.ToString().Trim();
                                    img.Save(newpath, ImageFormat.Png);   //保存
                                    o.isneedupload = false;
                                    result = qr_StoreService.Instance.Update_Entity(o);
                                }
                                else
                                {
                                    result = false;
                                    //ErroCount += 1;//不可访问也失败
                                }
                                #endregion
                            }
                            else
                            {
                                result = false;
                                //ErroCount += 1;//qr_DiyCode没有记录也失败
                                ComLib.LogLib.Log4NetBase.Log("0-0、---------------导出门店图片失败::qr_DiyCode没有记录" + info + "---------------");
                            }
                            if (result == true)
                            {
                                SuccessCount += 1;
                                ComLib.LogLib.Log4NetBase.Log("3、---------------导出门店图片成功::" + info + "---------------");
                            }
                            else
                            {
                                ErroCount += 1;
                                ComLib.LogLib.Log4NetBase.Log("3、---------------导出门店图片失败::" + info + "---------------");
                            }
                            #endregion
                        }
                        else
                        {
                            ErroCount += 1;//qr_QrCodeRelate没关联记录也失败
                            ComLib.LogLib.Log4NetBase.Log("0-0、---------------导出门店图片失败::qr_QrCodeRelate没关联记录;门店ID:" + o.StoreCode + "---------------");
                        }
                    }
                    #endregion

                    if (nclist.Count > 0)
                    {
                        //4.打包图片成zip文件
                        #region 片成zip文件
                        zip_http.ZipFolderContents(path, zipPath + ".zip");
                        ComLib.LogLib.Log4NetBase.Log("4、---------------导出门店图片结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------");
                        JscriptMsg("导出门店图片结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------", "Index.aspx", "Success");
                        #endregion

                        //5、通知浏览器下载文件而不是打开  
                        #region 浏览器下载文件
                        //以字符流的形式下载文件  
                        FileStream fs = new FileStream(zipPath + ".zip", FileMode.Open);
                        byte[] bytes = new byte[(int)fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();
                        Response.ContentType = "application/octet-stream";
                        Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMdd") + "门店二维码图片.zip", System.Text.Encoding.UTF8));
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        //Response.End();
                        #endregion
                    }
                    else
                    {
                        ComLib.LogLib.Log4NetBase.Log("4、---------------导出门店图片结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------");
                        JscriptMsg("导出门店图片结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------", "Index.aspx", "Success");
                    }
                }
                else {
                    JscriptMsg("暂无图片导出", "Index.aspx", "Success");
                }

                #endregion
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("Exception、---------------导出门店图片异常错误:" + ex.Message + ex.StackTrace + info + "---------------");
                JscriptMsg("导出图片错误请联系管理员！", "Index.aspx", "Error");
            }
        }

        protected void btnEditCode_Click(object sender, EventArgs e)
        {

            #region 初始化变量
            int SuccessCount = 0;
            int ErroCount = 0;
            string info = "";
            #endregion

            //var store = qr_StoreService.Instance.Get_AllData_List();
            var store = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupdate == true, null);
            //if (entity == null) return false;

            #region 修改活动二维码
            var httpstr = ConfigurationManager.AppSettings["vigohttp"];
            var signsecret = ConfigurationManager.AppSettings["signscrect"];
            var result = false;
            ComLib.LogLib.Log4NetBase.Log("1-1、---------------查询得到门店共" + store.Count + "条---------------");
            for (int i = 0; i < store.Count; i++)
            {
                var o = store[i];
                ComLib.LogLib.Log4NetBase.Log("1-2、---------------正在执行第(" + i + ")条数据---------------");

                #region 编辑图文信息
                var extra = new List<ShareMarking.Interface.extra>() { 
                                    new ShareMarking.Interface.extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new ShareMarking.Interface.extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new ShareMarking.Interface.extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                #endregion

                var rel = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(qr_QrCodeRelate._.rel_Code == o.StoreCode && qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false);
                if (rel != null)
                {
                    info = "门店ID:" + o.StoreCode + "//门店名称:" + o.S_Name;
                    var message = new ShareMarking.Interface.message2()
                    {
                        id = rel.qr_CodeID.ToString(),
                        title = o.S_Name,
                        remark = o.S_Name + "的二维码",
                        sacode = "test",
                        extra = extra
                    };

                    #region vigo接口申请
                    var vigo = new ShareMarking.Interface.Qrcode_vigo(httpstr, signsecret);
                    var resultentity = vigo.UpdateQrcode(message);
                    //result = true;
                    #endregion

                    #region 更新门店
                    qr_Store entity = new qr_Store();
                    entity.StoreCode = o.StoreCode;
                    entity.S_Name = o.S_Name;
                    entity.S_Provinces = o.S_Provinces;
                    entity.S_City = o.S_City;
                    entity.S_Area = o.S_Area;
                    entity.S_Region = o.S_Region;
                    entity.ModifiedOn = DateTime.Now;
                    entity.A_wxTitle = o.A_wxTitle;
                    entity.A_wxImgUrl = o.A_wxImgUrl;
                    entity.A_wxDesc = o.A_wxDesc;
                    entity.A_wxUrl = o.A_wxUrl;
                    entity.isneedupdate = false;
                    if (qr_StoreService.Instance.Update_Entity(entity))
                    {
                        SuccessCount += 1;
                    }
                    else
                    {
                        ErroCount += 1;
                        ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新门店失败::" + info + "---------------");
                    }
                    #endregion
                }
                else
                {
                    ErroCount += 1;//qr_QrCodeRelate没关联记录也失败
                    ComLib.LogLib.Log4NetBase.Log("0-0、---------------更新门店失败::qr_QrCodeRelate没关联记录;" + info + "---------------");
                }                                              
            }
            ComLib.LogLib.Log4NetBase.Log("1-4、---------------更新门店结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------");
            #endregion

        }
    }
}